//
//  FilesManage.m
//  JXFile
//
//  Created by 祁俊喜 on 2024/4/12.
//

#import "FilesManage.h"
#import <QuickLookThumbnailing/QuickLookThumbnailing.h>

@implementation FilesManage


+ (NSString *)documentsPath {
    
    NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *dataFilePath = [docsDir stringByAppendingPathComponent:@"sharing"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:dataFilePath];
    if (!existed) {
        [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
        return dataFilePath;
    }else{
        ///var/mobile/Containers/Data/Application/7B81CFC2-787F-46E0-B01C-557A7A50B076/Documents/sharing
        return dataFilePath;
    }
}

+ (NSArray *)getAllFilesName{
    NSFileManager *fileManager = [NSFileManager defaultManager];
//    NSString *testDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *testDirectory = [self documentsPath];
    NSArray *files = [fileManager contentsOfDirectoryAtPath:testDirectory error:nil];
    return files;
}

//写文件
- (void)writeFile{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    NSString *testPath      = [testDirectory stringByAppendingPathComponent:@"test.txt"];
    NSString *content       = @"测试写入内容！";
    BOOL res = [content writeToFile:testPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (res) {
        NSLog(@"文件写入成功");
    }else{
        NSLog(@"文件写入失败");
    }
    
}

+(NSString *)getFileSize:(NSString *)fileName {
    NSString *path = [FilesManage documentsPath];
    path = [NSString stringWithFormat:@"%@/%@",path,fileName];
    NSFileManager* manager = [NSFileManager defaultManager];
    float size = [[manager attributesOfItemAtPath:path error:nil] fileSize];
    NSString *string = [NSByteCountFormatter stringFromByteCount:size countStyle:NSByteCountFormatterCountStyleFile];
    return string;
}

//删除文件
+ (void)deleteFile:(NSString *)fileName{
    NSString *documentsPath = [FilesManage documentsPath];
    NSString *directory = [documentsPath stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL res=[fileManager removeItemAtPath:directory error:nil];
    if (res) {
        NSLog(@"文件删除成功");
    }else{
        NSLog(@"文件删除失败");
    }
}

+ (void)deleteDZMeBookRead:(NSString *)fileName{
    if ([fileName hasSuffix:@"txt"]) {
        fileName = [fileName stringByDeletingPathExtension];
        NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        docsDir = [docsDir stringByAppendingPathComponent:@"DZMeBookRead"];
        NSString *directory = [docsDir stringByAppendingPathComponent:fileName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        BOOL res=[fileManager removeItemAtPath:directory error:nil];
        if (res) {
            NSLog(@"文件删除成功");
        }else{
            NSLog(@"文件删除失败");
        }
        NSLog(@"文件是否存在: %@",[fileManager isExecutableFileAtPath:directory]?@"YES":@"NO");
    }
    
}

//读文件
- (void)readFile{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    NSString *testPath      = [testDirectory stringByAppendingPathComponent:@"test.txt"];
    NSString *content       = [NSString stringWithContentsOfFile:testPath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"文件读取成功: %@",content);
}

/** string格式转换为超文本HTML格式*/
+ (NSString *)htmlStringByAttributeString:(NSString *)string {
    NSAttributedString *htmlAttributeString = [[NSAttributedString alloc] initWithString:string];
    NSString *htmlString;
    NSDictionary *exportParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                   NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]
                                   };
    NSData *htmlData = [htmlAttributeString dataFromRange:NSMakeRange(0, htmlAttributeString.length) documentAttributes:exportParams error:nil];
    htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
    return htmlString;
}

+(UIImage *)getImage:(NSString *)fileName {
    NSString *path = [NSString stringWithFormat:@"file://%@/%@",[FilesManage documentsPath],fileName];
    NSURL *url = [NSURL URLWithString:path];
    dispatch_semaphore_t signal = dispatch_semaphore_create(0);
    __block UIImage *image = nil;
    if (url) {
        CGSize thumbnailSize = CGSizeMake(24 * UIScreen.mainScreen.scale, 24 * UIScreen.mainScreen.scale);
        QLThumbnailGenerationRequest *request =  [[QLThumbnailGenerationRequest alloc] initWithFileAtURL:url size:thumbnailSize scale:UIScreen.mainScreen.scale representationTypes:QLThumbnailGenerationRequestRepresentationTypeLowQualityThumbnail];
        [QLThumbnailGenerator.sharedGenerator generateRepresentationsForRequest:request updateHandler:^(QLThumbnailRepresentation * _Nullable thumbnail, QLThumbnailRepresentationType type, NSError * _Nullable error) {
            image = thumbnail.UIImage;
            dispatch_semaphore_signal(signal);
         }];
    }
    dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
    if ([fileName hasSuffix:@"png"]) {
        return [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    }
    if ([fileName hasSuffix:@"zip"]) {
        return [UIImage imageNamed:@"yp_icon_fileZip_Normal"];
    }
    if ([fileName hasSuffix:@"docx"]) {
        return [UIImage imageNamed:@"yp_icon_fileTxt_Normal"];
    }
    if (!image) {
        return [UIImage imageNamed:@"yp_icon_fileUnknow_Normal"];
    }
    return image;
}

+(UIWindow*)getCurrentWindow {
    if([[[UIApplication sharedApplication] delegate] window]) {
        return[[[UIApplication sharedApplication] delegate] window];
    }else{
        if (@available(iOS 13.0, *))  {
            NSArray *array =[[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene* windowScene = (UIWindowScene*)array[0];
            UIWindow* mainWindow = [windowScene valueForKeyPath:@"delegate.window"];
            if(mainWindow) {
                return mainWindow;
            }else{
                return [UIApplication sharedApplication].windows.firstObject;
            }
        }else{
            return [UIApplication sharedApplication].keyWindow;
        }
    }
}

+(NSString *)usedSpaceAndfreeSpace{

    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()];
    NSDictionary *results = [fileURL resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:nil];

    NSString *deviceFreeMemory = [NSByteCountFormatter stringFromByteCount:[results[NSURLVolumeAvailableCapacityForImportantUsageKey] longLongValue] countStyle:NSByteCountFormatterCountStyleFile];
    
    NSDictionary *totalResults = [fileURL resourceValuesForKeys:@[NSURLVolumeTotalCapacityKey] error:nil];

    NSString *totalMemory = [NSByteCountFormatter stringFromByteCount:[totalResults[NSURLVolumeTotalCapacityKey] longLongValue] countStyle:NSByteCountFormatterCountStyleFile];
    
    return [NSString stringWithFormat:@"可用空间%@/%@",deviceFreeMemory,totalMemory];
}

//获取文件夹大小

+(NSString *)folderSize:(NSString *)folderPath {
    folderPath = [NSString stringWithFormat:@"%@/%@",[self documentsPath],folderPath];
    NSString *total = [NSByteCountFormatter stringFromByteCount:[self folderSizeAtPath:folderPath] countStyle:NSByteCountFormatterCountStyleFile];
    return total;
}

+ (long long)folderSizeAtPath:(NSString *)folderPath {
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:folderPath]) {
        return 0;
    }else{
        NSEnumerator *enumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
        NSString *fileName;
        long long folderSize = 0;
        while ((fileName = [enumerator nextObject]) != nil) {
            NSString *fileAbsolutePaht = [folderPath stringByAppendingPathComponent:fileName];
            folderSize += [self folderSizeAtPath:fileAbsolutePaht];
        }
        return folderSize;
    }
}

//判断是文件还是文件夹
+(BOOL)isDirectory:(NSString *)filePath {
    BOOL isDir = NO;
    [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir];
    return isDir;
}


@end
